package com.hushao.lims.weblims.controller;
import com.hushao.lims.weblims.domain.Role;
import com.hushao.lims.weblims.domain.TeacherInfo;
import com.hushao.lims.weblims.service.RoleService;
import com.hushao.lims.weblims.service.TeacherService;
import com.hushao.lims.weblims.util.ExcelUtil;
import com.hushao.lims.weblims.utils.UserUtil;
import com.hushao.lims.weblims.vo.ResponseData;
import com.hushao.lims.weblims.vo.RoleVo;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 930588706
 * @date 18/2/1
 * 教师
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserUtil userUtil;

    /**
     * 模糊查看教师列表（分页）
     * @param teacherName
     * @param async
     * @param pageable
     * @param model
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "查看教师集合（分页")
    @PreAuthorize("hasAnyAuthority('ROLE_主管','ROLE_管理员','ROLE_超级管理员')")
    @GetMapping
    public String teacherList(@RequestParam(value = "teacherName",required = false,defaultValue = "")String teacherName,
                              @RequestParam(value = "async",required = false) boolean async,
                              Pageable pageable,
                              Model model) throws Exception{
        Page<TeacherInfo> teacherInfoPage=teacherService.listByName(teacherName,pageable);
        List<TeacherInfo> teachers=teacherInfoPage.getContent();
        model.addAttribute("page",teacherInfoPage);
        model.addAttribute("teachers",teachers);
        TeacherInfo teacher= userUtil.isLogged(SecurityContextHolder.getContext().getAuthentication());
        //获取数据库的角色而不是获取当前静态登陆角色
        TeacherInfo teacher1=teacherService.getById(teacher.getTeacherId());
        //是否是超级管理员
        boolean isAdministrator=userUtil.isAdministrator(teacher1);
        boolean isAdmin=false;
        if(isAdministrator){
            isAdmin=true;
        }else {
            isAdmin=userUtil.isAdmin(teacher1);
        }
        model.addAttribute("isBo",isAdmin);
        model.addAttribute("isAuthority",isAdministrator);
        return async==true?"teachers/list ::#mainContainerRepleace":"teachers/list";
    }

    /**
     * 获取添加教师界面
     * @param model
     * @return
     */
    @ApiOperation(value = "添加教师界面")
    @PreAuthorize("hasAnyAuthority('ROLE_管理员','ROLE_超级管理员')")
    @GetMapping("/add")
    public String addInterface(Model model){
        TeacherInfo teacherInfo=new TeacherInfo(null,null, null,null,null,null);
        model.addAttribute("teacher",teacherInfo);
        return "/teachers/edit";
    }

    /**
     * 获取编辑教师界面
     * @param teacherId
     * @param model
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ROLE_管理员','ROLE_超级管理员')")
    @GetMapping("/edit/{teacherId}")
    public String editInterface(@PathVariable("teacherId") Integer teacherId, Model model){
        TeacherInfo teacherInfo=teacherService.getById(teacherId);
        model.addAttribute("teacher",teacherInfo);
        return "/teachers/edit";
    }

    /**
     * 增加或修改教师
     * @param teacher
     * @param departmentName
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "添加或修改教师服务")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ROLE_管理员','ROLE_超级管理员')")
    @PostMapping
    public ResponseData saveOrUpdate(TeacherInfo teacher,String departmentName)throws Exception{
        String message=teacherService.saveOrUpdate(teacher,departmentName);
        return new ResponseData(true,message);
    }

    /**
     * 删除教师成功
     * @param teacherId
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "删除教师信息服务")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ROLE_管理员','ROLE_超级管理员')")
    @DeleteMapping("/{teacherId}")
    public ResponseData delete(@PathVariable("teacherId") Integer teacherId)throws Exception {
        teacherService.remove(teacherId);
        return new ResponseData(true,"删除成功！");
    }

    /**
     * 获取教师授权界面
     * @param teacherId
     * @param model
     * @return
     */
    @ApiOperation(value = "获取教师授权界面")
    @PreAuthorize("hasAuthority('ROLE_超级管理员')")
    @GetMapping("/{teacherId}/authority")
    public String authorityInterface(@PathVariable("teacherId") Integer teacherId, Model model){
        TeacherInfo teacher=teacherService.getById(teacherId);
        List<Role> roles=roleService.getRoles();
        List<RoleVo> roleVos=new ArrayList<>();

        for (Role r: roles) {
            //查找当前角色是否有此权限
           boolean isExist= teacher.getRoles().stream().anyMatch(e->e.getRoleName().equals(r.getRoleName()));
           RoleVo roleVo;
           if (isExist){
               roleVo=new RoleVo(r.getRoleId(),r.getRoleName().substring(5,r.getRoleName().length()),"true");
           }else {
               roleVo=new RoleVo(r.getRoleId(),r.getRoleName().substring(5,r.getRoleName().length()),"false");
           }
           roleVos.add(roleVo);
        }
        model.addAttribute("roleVos",roleVos);
        model.addAttribute("teacherId",teacherId);
        return "/teachers/authority";
    }

    /**
     * 教师授权
     * @param teacherId
     * @return
     */
    @ApiOperation(value = "教师授权服务")
    @PreAuthorize("hasAuthority('ROLE_超级管理员')")
    @PostMapping("/{teacherId}/authority")
    @ResponseBody
    public ResponseData authority(@PathVariable("teacherId") Integer teacherId, @RequestParam(value = "roleIds") Integer[] roleIds)throws Exception{
        TeacherInfo teacher=teacherService.getById(teacherId);
        teacherService.authority(teacher,roleIds);
        return new ResponseData(true,"授权成功!");
    }

    /**
     * 导入教师信息
     * @return
     */
    @ApiOperation(value = "批量导入教师Excel信息文件")
    @PreAuthorize("hasAnyAuthority('ROLE_管理员','ROLE_超级管理员')")
    @PostMapping("/upload")
    @ResponseBody
    public ResponseData uploadFiles(@RequestParam("file") MultipartFile file)throws Exception{
        Workbook wb=null;
        if (ExcelUtil.isExcel2007(file.getOriginalFilename())) {
            wb = new XSSFWorkbook(file.getInputStream());
        } else {
            wb = new HSSFWorkbook(file.getInputStream());
        }

        teacherService.uploadFile(wb.getSheetAt(0));
        wb.close();
        return new ResponseData(true,"导入成功!");
    }

    /**
     * 教师课表
     * @param teacherId
     * @param model
     * @return
     */
    @ApiOperation(value = "获取教师课表")
    @GetMapping("/{teacherId}/timetables")
    public String timetables(@PathVariable("teacherId") Integer teacherId, Model model)throws Exception{
        TeacherInfo teacher=teacherService.getById(teacherId);
        Map<String, Map<String, String>> map=teacherService.timetables(teacher);
        model.addAttribute("map",map);
        return "/teachers/timetables";
    }
}
